package com.tyut.musicdreamer.service.music.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tyut.musicdreamer.service.music.model.dto.PlaylistCreateRequest;
import com.tyut.musicdreamer.service.music.model.entity.Playlist;
import com.tyut.musicdreamer.service.music.model.vo.MusicVO;
import com.tyut.musicdreamer.service.music.model.vo.PlaylistVO;
import com.tyut.musicdreamer.service.music.model.vo.Result;
import com.tyut.musicdreamer.service.music.service.PlaylistService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 歌单接口
 */
@Slf4j
@RestController
@RequestMapping("/api/music/playlist")
@RequiredArgsConstructor
public class PlaylistController {

    private static final String USER_ID_ATTRIBUTE = "userId";
    private static final String USER_ID_HEADER = "X-User-Id";
    
    private final PlaylistService playlistService;
    private final HttpServletRequest request;
    
    /**
     * 获取当前用户ID
     * 从请求头X-User-Id中获取，如果获取不到，则尝试从请求属性中获取
     * 如果都没有，则使用默认值1
     */
    private Long getCurrentUserId() {
        // 尝试从请求头中获取用户ID
        String userIdHeader = request.getHeader(USER_ID_HEADER);
        if (userIdHeader != null && !userIdHeader.isEmpty()) {
            try {
                log.debug("从请求头获取到用户ID: {}", userIdHeader);
                return Long.parseLong(userIdHeader);
            } catch (NumberFormatException e) {
                log.warn("请求头中的用户ID不是有效的数字: {}", userIdHeader);
            }
        }
        
        // 如果请求头中没有，则尝试从请求属性中获取
        Object userIdAttr = request.getAttribute(USER_ID_ATTRIBUTE);
        if (userIdAttr != null) {
            log.debug("从请求属性获取到用户ID: {}", userIdAttr);
            if (userIdAttr instanceof Number) {
                return ((Number) userIdAttr).longValue();
            } else if (userIdAttr instanceof String) {
                try {
                    return Long.parseLong((String) userIdAttr);
                } catch (NumberFormatException e) {
                    log.warn("请求属性中的用户ID不是有效的数字: {}", userIdAttr);
                }
            }
        }
        
        // 未获取到用户ID，返回默认值1
        log.warn("无法获取当前用户ID，使用默认值1");
        return 1L;
    }

    /**
     * 创建歌单
     */
    @PostMapping("/create")
    public Result<Long> createPlaylist(@RequestBody @Valid PlaylistCreateRequest request) {
        log.info("创建歌单: {}", request);
        Long userId = getCurrentUserId();
        log.info("当前用户ID: {}", userId);
        Long playlistId = playlistService.createPlaylist(userId, request);
        return Result.success(playlistId);
    }

    /**
     * 获取歌单详情
     */
    @GetMapping("/detail/{playlistId}")
    public Result<PlaylistVO> getPlaylistDetail(@PathVariable Long playlistId) {
        log.info("获取歌单详情: {}", playlistId);
        PlaylistVO playlist = playlistService.getPlaylistDetail(playlistId);
        return Result.success(playlist);
    }

    /**
     * 获取歌单中的歌曲列表
     */
    @GetMapping("/{playlistId}/songs")
    public Result<List<MusicVO>> getPlaylistSongs(@PathVariable Long playlistId) {
        log.info("获取歌单歌曲列表: playlistId={}", playlistId);
        List<MusicVO> songs = playlistService.getPlaylistMusics(playlistId);
        return Result.success(songs);
    }

    /**
     * 获取当前用户的歌单列表
     */
    @GetMapping("/my")
    public Result<List<PlaylistVO>> getMyPlaylists() {
        log.info("获取当前用户歌单列表");
        Long userId = getCurrentUserId();
        log.info("当前用户ID: {}", userId);
        List<PlaylistVO> playlists = playlistService.getUserPlaylists(userId);
        return Result.success(playlists);
    }

    /**
     * 获取用户的歌单列表
     */
    @GetMapping("/user/{userId}")
    public Result<List<PlaylistVO>> getUserPlaylists(@PathVariable Long userId) {
        log.info("获取用户歌单列表: userId={}", userId);
        List<PlaylistVO> playlists = playlistService.getUserPlaylists(userId);
        return Result.success(playlists);
    }

    /**
     * 分页获取歌单列表
     */
    @GetMapping("/page")
    public Result<Page<PlaylistVO>> getPlaylistPage(
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "10") Long size) {
        log.info("分页获取歌单列表: current={}, size={}", current, size);
        Page<Playlist> page = new Page<>(current, size);
        Page<PlaylistVO> result = playlistService.getPlaylistPage(page);
        return Result.success(result);
    }

    /**
     * 更新歌单信息
     */
    @PutMapping("/update/{playlistId}")
    public Result<Boolean> updatePlaylist(
            @PathVariable Long playlistId,
            @RequestBody @Valid PlaylistCreateRequest request) {
        log.info("更新歌单信息: playlistId={}, request={}", playlistId, request);
        Long userId = getCurrentUserId();
        boolean success = playlistService.updatePlaylist(userId, playlistId, request);
        return Result.success(success);
    }

    /**
     * 删除歌单
     */
    @DeleteMapping("/delete/{playlistId}")
    public Result<Boolean> deletePlaylist(@PathVariable Long playlistId) {
        log.info("删除歌单: playlistId={}", playlistId);
        Long userId = getCurrentUserId();
        boolean success = playlistService.deletePlaylist(userId, playlistId);
        return Result.success(success);
    }

    /**
     * 添加歌曲到歌单
     */
    @PostMapping("/{playlistId}/add")
    public Result<Integer> addMusicsToPlaylist(
            @PathVariable Long playlistId,
            @RequestBody List<Long> musicIds) {
        log.info("添加歌曲到歌单: playlistId={}, musicIds={}", playlistId, musicIds);
        Long userId = getCurrentUserId();
        int count = playlistService.addMusicsToPlaylist(userId, playlistId, musicIds);
        return Result.success(count);
    }

    /**
     * 从歌单中移除歌曲
     */
    @PostMapping("/{playlistId}/remove")
    public Result<Integer> removeMusicsFromPlaylist(
            @PathVariable Long playlistId,
            @RequestBody List<Long> musicIds) {
        log.info("从歌单中移除歌曲: playlistId={}, musicIds={}", playlistId, musicIds);
        Long userId = getCurrentUserId();
        int count = playlistService.removeMusicsFromPlaylist(userId, playlistId, musicIds);
        return Result.success(count);
    }

    /**
     * 更新歌单封面
     */
    @PutMapping("/{playlistId}/cover")
    public Result<Boolean> updatePlaylistCover(
            @PathVariable Long playlistId,
            @RequestParam String coverUrl) {
        log.info("更新歌单封面: playlistId={}, coverUrl={}", playlistId, coverUrl);
        Long userId = getCurrentUserId();
        boolean success = playlistService.updatePlaylistCover(userId, playlistId, coverUrl);
        return Result.success(success);
    }
} 